local uri = ngx.var.uri
local index = string.find(uri, "([0-9]+)x([0-9]+)");
if index == nil then
	ngx.exit(404)
end

local originalUrl = string.sub(uri, 0, index - 2)
local area = string.sub(uri, index)
index = string.find(area, "([.])")
if index == nil then
	ngx.exit(404)
end
originalUrl = originalUrl..string.sub(area, index)
area = string.sub(area, 0, index - 1)


local  image_sizes = {"80x80", "800x600", "40x40"};
function table.contains( table, element )
	for _, value in pairs(table) do
		if value == element then
			return true
		end
	end
	return false
end

--ngx.header.content_type = "text/plain";
if table.contains(image_sizes, area) then
	--local command = "/usr/local/bin/gm convert "..ngx.var.image_root..originalUrl.." -thumbnail "..area.." -background white -gravity center -extent "..area.." "..ngx.var.file;
	local command = "/usr/local/bin/gm convert "..
		ngx.var.image_root..originalUrl..
		" -resize "..area.."^"..
		" -crop "..area..
		" -background white -gravity center -extent "..area.." "..ngx.var.file;
	ngx.log(ngx.WARN, command)
	os.execute(command);
else
	ngx.exit(404);
end